/*! Jquery NSelect Plugin - v3.0.2
* jquery多级联调插件
* http://git.oschina.net/kictto/JqueryCombinedCommissioningPlugin
* Author: Kictto 
* QQ: 994580411
* Copyright (c) 2015 Kictto; Licensed Apache */
(function($) {
	var selectBindStack = {};
	var defaults = { //定义默认的配置
		value: 1,
		source: [{
			value: 1,
			text: '请选择'
		}],
		success: null
	}
	var methods = {
		init: function(dom, options, key, value) {},
		main: function(dom) {},
	}

	function init(dfd, dom, selt,options, key, value) {
		if (typeof options == 'object') {
			var config = $.extend({},defaults, options);
			//如果内联属性中标注了data-value，那么会覆盖option中的value
			if (typeof $(dom).attr('data-value') == 'string') {
				config.value = $(dom).attr('data-value');
			}
			selectBindStack[selt] = config;
		} else if (typeof options == 'string') {
			switch (options) {
				case 'option':
					selectBindStack[selt][key] = value;
					break;
			}
		}
		dfd.resolve();
	};

	function main(dom,selt) {
		var config = selectBindStack[selt];
		var source; //定义一个存储选项的对象
		var dfdm = $.Deferred();
		if ((typeof config.source) === 'string') { //对应处理source给的是一个链接
			$.ajax({
				type: "get",
				url: config.source,
				async: true,
				success: function(res) {
					source = res;
					dfdm.resolve();
				}
			});
		} else { //对应处理source给的是一个对象(该对象必须为一个数组，类似于defaults中定义的一样)
			source = config.source;
			dfdm.resolve();
		}
		dfdm.done(function() {
			$(dom).empty();
			$.each(source, function(key, obj) {
				var selected = (obj.value == config.value) ? 'selected' : '';
				$(dom).append('<option value="' + obj.value + '" ' + selected + '>' + obj.text + '</option>');
			});
		});
		$(dom).change(function() {
			var seltt='sel'+dom.selector;
			var config=selectBindStack[selt];
			var newValue = $(dom).children('option:selected').val();
			$(dom).attr("data-value",newValue);
			if (typeof config.success == 'function') {
				config.success.call(config.success, newValue);
			}
		});
	};
	$.fn.select = function(options, key, value) {
		if (this.length > 1) {
			return this.each(function() {
				var dom=this;
				var selt=this.selector;
				var dfd = $.Deferred();
				init(dfd, dom, selt,options, key, value);
				dfd.done(function() {
					main(dom,selt);
				});
			});
		} else {
			var dom=this;
			var selt=this.selector;
			var dfd = $.Deferred();
			init(dfd, dom, selt,options, key, value);
			dfd.done(function() {
				main(dom,selt);
			});
			return this;
		}
	}

})(jQuery);